﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Input;
using Socium.Domain;
using Socium.Domain.Collections;
using Socium.Domain.Tests.Testings;
using Socium.Persons;
using Socium.Presentation;

namespace Socium.Testings {
	class TestingViewModel : PageViewModel {
		public TestingViewModel(Testing testing, Database database) : base(testing.ToString()) {
			_testing = testing;

			DisplayName = testing.Date.ToString();

			_tests.AddRange(testing.Tests.MapLazy(test => new TestTreeItem(test)));
			_persons.AddRange(database.Persons.MapLazy(person => new PersonLineItem(person)));

			SaveCommand = new Command(Save, CanSave);
		}

		readonly Testing _testing;

		public void Save() {
			if (!CanSave()) {
				throw new InvalidOperationException();
			}

			_tests.Iterate(item => item.Save(_selected_person.Model, _testing));
		}

		public bool CanSave() {
			return SelectedPerson != null;
		}

		void UpdateAnswers() {
			if (SelectedPerson != null) {
				_tests.Iterate(item => item.Load(SelectedPerson.Model, _testing));
			}
		}

		#region Persons

		readonly ObservableCollection<PersonLineItem> _persons = new ObservableCollection<PersonLineItem>();

		public IEnumerable<PersonLineItem> Persons {
			get { return _persons; }
		}

		#endregion

		#region SelectedPerson

		PersonLineItem _selected_person;

		public PersonLineItem SelectedPerson {
			get { return _selected_person; }
			set {
				_selected_person = value;
				OnPropertyChanged("SelectedPerson");

				UpdateAnswers();
			}
		}

		#endregion

		#region Tests

		readonly ObservableCollection<TestTreeItem> _tests = new ObservableCollection<TestTreeItem>();

		public IEnumerable<TestTreeItem> Tests {
			get { return _tests; }
		}

		#endregion

		#region SaveCommand

		public ICommand SaveCommand { get; private set; }

		#endregion

	}
}
